/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package main;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import helper.Utilities;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import model.Request;
import model.Response;

/**
 *
 * @author Hallucinogen
 */
public class TrackerHandler implements HttpHandler{

    public TrackerHandler(Tracker tracker) {
        m_Tracker = tracker;
    }

    public void handle(HttpExchange he) throws IOException {
        String requestMethod = he.getRequestMethod();

        if (requestMethod.equalsIgnoreCase("GET")){
            String query = he.getRequestURI().getQuery();

            Request req = Request.decodeRequest(query);

            InetSocketAddress peerAddr = he.getRemoteAddress();
            Peer peer = new Peer(he.getRemoteAddress().getAddress().getHostAddress());
            peer.setData(req);
            peer.setAddress(peerAddr);

            m_Tracker.onPeerRequestFile(req.getFileName(), peer);

            ArrayList<Peer> peers = m_Tracker.getPeers(req.getFileName(), peer);

            Response response = new Response();
            response.setComplete(Peer.getCompletePeersCount(peers));
            /// TODO : failure reason and warning?
            response.setFailureReason("");
            response.setWarningMessage("");
            response.setInterval(Utilities.INTERVAL);
            response.setIncomplete(Peer.getIncompletePeersCount(peers));
            response.setPeers(peers);

            String resp = response.encodeResponse();

            he.sendResponseHeaders(200, resp.length());
            OutputStream os = he.getResponseBody();
            os.write(resp.getBytes());
            os.close();
        }

        he.close();
    }

    private Tracker m_Tracker;
}
